using FytSoa.Domain.Cms;
using FytSoa.Sugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using MapsterMapper;
using FytSoa.Common.Utils;
using FytSoa.Domain.Core.Param;
using FytSoa.Domain.Core.Result;
using Masuit.Tools.Linq;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Cms;

/// <summary>
/// 模板表 服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v2")]
public class CmsTemplateService : SugarRepository<CmsTemplate>,ICmsTemplateService 
{
    private readonly IMapper _mapper;
    public CmsTemplateService(IMapper mapper)
    {
        _mapper = mapper;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ApiResult<PageResult<CmsTemplateDto>>> GetPagesAsync(PageParam param)
    {
        var where = Expressionable.Create<CmsTemplate>();
        var (list,totalItems,totalPage) = await base.GetPageResultAsync(where.ToExpression(), param.Page, param.Limit, m => m.Id);
        var result = new PageResult<CmsTemplateDto>()
        {
            Items = _mapper.Map<List<CmsTemplateDto>>(list),
            TotalItems = totalItems,
            TotalPages = totalPage
        };
        return JResult<PageResult<CmsTemplateDto>>.Success(result);
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ApiResult<CmsTemplateDto>> GetAsync(long id)
    {
        return JResult<CmsTemplateDto>.Success(_mapper.Map<CmsTemplateDto>(await base.GetByIdAsync(id)));
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<ApiResult<bool>> AddAsync(CmsTemplateDto model)
    {
        model.Id = Unique.Id();
        return JResult<bool>.Success(await base.InsertAsync(_mapper.Map<CmsTemplate>(model)));
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<ApiResult<bool>> ModifyAsync(CmsTemplateDto model)
    {
        return JResult<bool>.Success(await base.UpdateAsync(_mapper.Map<CmsTemplate>(model)));
    }

    /// <summary>
    /// 删除,支持多个
    /// </summary>
    /// <param name="ids">逗号分隔</param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<ApiResult<bool>> DeleteAsync(string ids)
    {
        return JResult<bool>.Success(await base.DeleteAsync(m=>ids.StrToListLong().Contains(m.Id)));
    }
}
